<template>
  <div class="container">
    <!-- 固定导航 -->
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.push('/layout/user')"
      title="小思同学"
    ></van-nav-bar>
    <!-- 聊天主体区域 -->
    <div class="chat-list">
      <div v-for="(item, inedx) in list" :key="inedx">
        <!-- 左侧是机器人小思 -->
        <div ref="chatItem" class="chat-item left" v-if="item.name === 'xs'">
          <van-image
            fit="cover"
            round
            src="https://img.yzcdn.cn/vant/cat.jpeg"
          />
          <div class="chat-pao">{{ item.msg }}</div>
        </div>

        <!-- 右侧是当前用户 -->
        <div ref="chatItem" class="chat-item right" v-if="item.name === 'me'">
          <div class="chat-pao">{{ item.msg }}</div>
          <van-image fit="cover" round :src="$store.state.userInfo.photo" />
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top">
      <van-field
        placeholder="说点什么..."
        v-focus
        v-model.trim="word"
        @keydown.enter="emitFn"
      >
        <template #button>
          <span style="font-size: 12px; color: #999" @click="emitFn">发送</span>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import { io } from 'socket.io-client'
import { Toast } from 'vant'
let socket = null
export default {
  name: 'Chat',
  data () {
    return {
      word: '', // 输入框的内容
      // 所有的聊天消息
      list: JSON.parse(localStorage.getItem('chatlist')) || [{ name: 'xs', msg: '有什么可以帮助你的嘛' }]
    }
  },
  activated () {
    this.$nextTick(() => {
      this.scrollFn()
    })
    // 1.  连接服务器
    socket = io('ws://toutiao.itheima.net', {
      query: {
        token: this.$store.state.token
      },
      transports: ['websocket']
    })
    // 2. 监听连接成功事件
    socket.on('connect', () => {
      // 4.接收
      socket.on('message', (data) => {
        // 将获取的数据同步到本地
        this.list.push({ name: 'xs', msg: data.msg })
        this.$nextTick(() => {
          this.scrollFn()
        })
      })
    })
  },
  methods: {
    emitFn () {
      if (!this.word) return Toast.fail('内容不能为空!')
      //  3.发送消息
      socket.emit('message', {
        msg: this.word,
        timestamp: new Date()
      })
      // 将发送的数据同步到本地
      this.list.push({ name: 'me', msg: this.word })
      // 清空输入框
      this.word = ''
      this.$nextTick(() => {
        this.scrollFn()
      })
    },
    scrollFn () {
      const items = this.$refs.chatItem
      const item = items[items.length - 1]
      item.scrollIntoView({
        behavior: 'smooth'
      })
    }
  },
  destroyed () {
    // 退出断开连接
    socket && socket.close()
  },
  watch: {
    list (newval) {
      localStorage.setItem('chatlist', JSON.stringify(newval))
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
  padding: 46px 0 50px 0;
  .chat-list {
    height: 100%;
    overflow-y: scroll;
    .chat-item {
      padding: 10px;
      .van-image {
        vertical-align: top;
        width: 40px;
        height: 40px;
      }
      .chat-pao {
        vertical-align: top;
        display: inline-block;
        min-width: 40px;
        max-width: 70%;
        min-height: 40px;
        line-height: 38px;
        border: 0.5px solid #c2d9ea;
        border-radius: 4px;
        position: relative;
        padding: 0 10px;
        background-color: #e0effb;
        word-break: break-all;
        font-size: 14px;
        color: #333;
        &::before {
          content: "";
          width: 10px;
          height: 10px;
          position: absolute;
          top: 12px;
          border-top: 0.5px solid #c2d9ea;
          border-right: 0.5px solid #c2d9ea;
          background: #e0effb;
        }
      }
    }
  }
}
.chat-item.right {
  text-align: right;
  .chat-pao {
    margin-left: 0;
    margin-right: 15px;
    &::before {
      right: -6px;
      transform: rotate(45deg);
    }
  }
}
.chat-item.left {
  text-align: left;
  .chat-pao {
    margin-left: 15px;
    margin-right: 0;
    &::before {
      left: -5px;
      transform: rotate(-135deg);
    }
  }
}
.reply-container {
  position: fixed;
  left: 0;
  bottom: 0;
  height: 44px;
  width: 100%;
  background: #f5f5f5;
  z-index: 9999;
}
</style>
